'use client';

import React, { useState } from 'react';
import { Card, Form, Input, Button, Avatar, Upload, message, Divider, Space, Tag } from 'antd';
import { UserOutlined, MailOutlined, EditOutlined, CameraOutlined } from '@ant-design/icons';
import { useAuth, AuthGuard } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import type { UploadProps } from 'antd';

interface ProfileForm {
  displayName: string;
  email: string;
}

interface PasswordForm {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

function ProfileContent() {
  const { user, updateUser } = useAuth();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [passwordLoading, setPasswordLoading] = useState(false);
  const [profileForm] = Form.useForm<ProfileForm>();
  const [passwordForm] = Form.useForm<PasswordForm>();

  // 更新个人信息
  const handleUpdateProfile = async (values: ProfileForm) => {
    setLoading(true);
    try {
      const response = await fetch('/api/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(values),
      });

      const data = await response.json();

      if (response.ok) {
        message.success('个人信息更新成功');
        updateUser(data.user);
      } else {
        message.error(data.error || '更新失败');
      }
    } catch (error) {
      console.error('更新个人信息失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleChangePassword = async (values: PasswordForm) => {
    if (values.newPassword !== values.confirmPassword) {
      message.error('两次输入的新密码不一致');
      return;
    }

    setPasswordLoading(true);
    try {
      const response = await fetch('/api/user/change-password', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          currentPassword: values.currentPassword,
          newPassword: values.newPassword,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        message.success('密码修改成功');
        passwordForm.resetFields();
      } else {
        message.error(data.error || '密码修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setPasswordLoading(false);
    }
  };

  // 头像上传配置
  const uploadProps: UploadProps = {
    name: 'avatar',
    action: '/api/user/avatar',
    headers: {
      authorization: 'Bearer ' + document.cookie.replace(/(?:(?:^|.*;)\s*auth-token\s*\=\s*([^;]*).*$)|^.*$/, "$1"),
    },
    showUploadList: false,
    beforeUpload: (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    onChange: (info) => {
      if (info.file.status === 'done') {
        message.success('头像上传成功');
        if (info.file.response?.avatar) {
          updateUser({ avatar: info.file.response.avatar });
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败');
      }
    },
  };

  if (!user) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">个人资料</h1>
          <p className="text-gray-600">管理您的个人信息和账户设置</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 用户信息卡片 */}
          <div className="lg:col-span-1">
            <Card className="text-center">
              <div className="mb-6">
                <div className="relative inline-block">
                  <Avatar
                    size={120}
                    src={user.avatar}
                    icon={<UserOutlined />}
                    className="mb-4"
                  />
                  <Upload {...uploadProps}>
                    <Button
                      type="primary"
                      shape="circle"
                      icon={<CameraOutlined />}
                      size="small"
                      className="absolute bottom-2 right-2 shadow-lg"
                    />
                  </Upload>
                </div>
              </div>
              
              <h3 className="text-xl font-semibold text-gray-800 mb-2">
                {user.displayName}
              </h3>
              <p className="text-gray-600 mb-4">@{user.username}</p>
              
              <Space direction="vertical" size="small" className="w-full">
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">角色:</span>
                  <Tag color={user.role === 'admin' ? 'red' : 'blue'}>
                    {user.role === 'admin' ? '管理员' : '用户'}
                  </Tag>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">状态:</span>
                  <Tag color={user.status === 'active' ? 'green' : 'orange'}>
                    {user.status === 'active' ? '正常' : '待激活'}
                  </Tag>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">邮箱验证:</span>
                  <Tag color={user.emailVerified ? 'green' : 'orange'}>
                    {user.emailVerified ? '已验证' : '未验证'}
                  </Tag>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">登录次数:</span>
                  <span className="font-medium">{user.loginCount}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">注册时间:</span>
                  <span className="text-sm">
                    {new Date(user.createdAt).toLocaleDateString('zh-CN')}
                  </span>
                </div>
              </Space>
            </Card>
          </div>

          {/* 编辑表单 */}
          <div className="lg:col-span-2 space-y-8">
            {/* 基本信息 */}
            <Card title="基本信息" extra={<EditOutlined />}>
              <Form
                form={profileForm}
                layout="vertical"
                initialValues={{
                  displayName: user.displayName,
                  email: user.email,
                }}
                onFinish={handleUpdateProfile}
              >
                <Form.Item
                  name="displayName"
                  label="显示名称"
                  rules={[
                    { required: true, message: '请输入显示名称' },
                    { min: 2, message: '显示名称至少需要2个字符' },
                  ]}
                >
                  <Input
                    prefix={<UserOutlined className="text-gray-400" />}
                    placeholder="请输入显示名称"
                    size="large"
                  />
                </Form.Item>

                <Form.Item
                  name="email"
                  label="邮箱地址"
                  rules={[
                    { required: true, message: '请输入邮箱地址' },
                    { type: 'email', message: '请输入有效的邮箱地址' },
                  ]}
                >
                  <Input
                    prefix={<MailOutlined className="text-gray-400" />}
                    placeholder="请输入邮箱地址"
                    size="large"
                  />
                </Form.Item>

                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    size="large"
                    className="w-full"
                  >
                    保存更改
                  </Button>
                </Form.Item>
              </Form>
            </Card>

            {/* 修改密码 */}
            <Card title="修改密码">
              <Form
                form={passwordForm}
                layout="vertical"
                onFinish={handleChangePassword}
              >
                <Form.Item
                  name="currentPassword"
                  label="当前密码"
                  rules={[{ required: true, message: '请输入当前密码' }]}
                >
                  <Input.Password
                    placeholder="请输入当前密码"
                    size="large"
                  />
                </Form.Item>

                <Form.Item
                  name="newPassword"
                  label="新密码"
                  rules={[
                    { required: true, message: '请输入新密码' },
                    { min: 6, message: '密码至少需要6个字符' },
                  ]}
                >
                  <Input.Password
                    placeholder="请输入新密码"
                    size="large"
                  />
                </Form.Item>

                <Form.Item
                  name="confirmPassword"
                  label="确认新密码"
                  rules={[
                    { required: true, message: '请确认新密码' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'));
                      },
                    }),
                  ]}
                >
                  <Input.Password
                    placeholder="请再次输入新密码"
                    size="large"
                  />
                </Form.Item>

                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={passwordLoading}
                    size="large"
                    className="w-full"
                    danger
                  >
                    修改密码
                  </Button>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </div>

        {/* 返回按钮 */}
        <div className="mt-8 text-center">
          <Button
            size="large"
            onClick={() => router.back()}
          >
            返回上一页
          </Button>
        </div>
      </div>
    </div>
  );
}

export default function ProfilePage() {
  return (
    <AuthGuard>
      <ProfileContent />
    </AuthGuard>
  );
}